<?php

namespace App\Http\Model;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Device extends Base
{
    protected $table = 'device';
    protected $channelLogTable = 'channel_log';

    protected $redisKeyParam = 'CACHE:DEVICE:%s';

    private $redisReportPlatform = 'DEVICE:REPORT:PLATFORM';

    private $redisReportSecondStay = 'DEVICE:SECOND:STAY:PLATFORM'; //记录需要上报次留的platform

    private $redisDeviceReportDay = 'DEVICE:REPORT:DAY:'; //记录上报次留的激活日期

    //渠道点击监测缓存数据
    protected $channelPlatformRequestKey = 'CHANNEL:PLATFORMREQUEST:';//string CHANNEL:PLATFORMREQUEST:{oaid/idfa}:{小写的值} => {string}

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    public function save($data = [])
    {
        $create = [
            'guid' => $data['guid'] ?? "",
            'imei' => $data['imei'] ?? "",
            'oaid' => $data['oaid'] ?? "",
            'idfa' => $data['idfa'] ?? "",
            'version_no' => $data['version_no'] ?? "",
            'os_name' => $data['os_name'] ?? "",
            'device' => $data['device'] ?? "",
            'channel_id' => $data['channel_id'] ?? "",
            'platform' => $data['platform'] ?? "",
            'risk_level' => $data['risk_level'] ?? "",
            'score' => $data['score'] ?? 0,
            'risk_type' => $data['risk_type'] ?? "",
            'callback' => $data['callback'] ?? "",
            'aid' => $data['aid'] ?? "",
            'cid' => $data['cid'] ?? "",
            'advertiser_id' => $data['advertiser_id'] ?? "",
            'ua' => $data['ua'] ?? "",
            'created_at' => time(),
        ];

        return DB::table($this->table)->insert($create);
    }

    //新增渠道推广记录
    public function insertChannelLog($data = [])
    {
        if(empty($data)) {
            return 0;
        }
        return DB::table($this->channelLogTable)->insertGetId($data);
    }

    //更新渠道推广记录
    public function updateChannelLog($id, $data=[])
    {
        $upData = [];
        if(isset($data['user_id'])) {
            $upData['user_id'] = (int) $data['user_id'];
        }
        if(!empty($upData)) {
            DB::table($this->channelLogTable)
                ->where('id', $id)
                ->update($upData);
        }

        return 1;
    }

    public function getByGuid($guid = '')
    {
        $devices=  DB::table($this->table)->where('guid', $guid)->get();
        return json_decode(json_encode($devices),true);
    }

    public function get($data = [], $isSingle = false)
    {
        if ($isSingle) {
            $result = DB::table($this->table)->where($data)->first();
            if (empty($result)) {
                return [];
            }
            return self::objToArray($result);
        } else {
            $result = DB::table($this->table)->where($data)->get()->toArray();
            return self::objToArray($result);
        }
    }

    public function updateDevice($data, $platform){
        return DB::table($this->table)->where($data)->update(['platform' => $platform]);
    }

    /**
     * 读取归因参数
     * @param $key
     * @return mixed
     */
    public function getParam($key)
    {
        $hashHey = sprintf($this->redisKeyParam, $key);
        $result = Redis::HGETALL($hashHey);
        return $result;
    }

    /**判断platform 是否需要上报注册和付费
     * @param $platform
     * @return bool
     */
    public function isNeedReportPlatform($platform){
        $report_arr = Redis::HGETALL($this->redisReportPlatform);
        $report_ids = empty($report_arr) ? [] : array_keys($report_arr);
        return in_array($platform ,$report_ids);
    }

    /**判断platform 是否需要上报次日留存
     * @param $platform
     * @return bool
     */
    public function isNeedReportSecondStay($platform){
        $platforms = Redis::HGETALL($this->redisReportSecondStay);
        $platform_arr = empty($platforms) ? [] : array_keys($platforms);
        return in_array($platform ,$platform_arr);
    }

    /**记录当天激活的设备
     * @param $guid
     * @param $callback
     */
    public function setDayReport($guid ,$callback){
        if(empty($guid)){
            return;
        }
        $key = $this->redisDeviceReportDay.date('Ymd');
        Redis::HSET($key ,$guid ,$callback);
        if (Redis::TTL($key) == -1) {
            Redis::EXPIRE($key, 2 * 24 * 3600);
        }
    }

    /**判断昨日是否激活
     * @param $guid
     * @return int
     */
    public function getBeforeDayReport($guid){
        $key = $this->redisDeviceReportDay.date('Ymd' ,strtotime('-1 days'));
        return Redis::HGET($key ,$guid) ?? '';
    }

    /**次留上报之后删除昨日激活记录，避免二次上报次留
     * @param $guid
     */
    public function delBeforeDayReport($guid){
        $key = $this->redisDeviceReportDay.date('Ymd' ,strtotime('-1 days'));
        Redis::HDEL($key ,$guid);
    }

    /**
     * 设置渠道点击监测缓存数据
     * @param $type 类型 oaid idfa
     * @param $code 具体的值
     * @param $params 详细数据
     */
    public function setChannelPlatformRequest($type, $code, $params)
    {
        $chacheKey = $this->channelPlatformRequestKey.$type.':'.strtolower($code);
        write_log('device','缓存key',$chacheKey);
        $result = Redis::SET($chacheKey, json_encode($params));
        write_log('device','缓存值',$result);
        Redis::EXPIRE($chacheKey, 86400);

        //去除中横线在存一下
        if($code !='') {
            $code = str_replace('-', '', $code);
            if($code !='') {
                $chacheKey = $this->channelPlatformRequestKey.$type.':'.strtolower($code);
                $result = Redis::SET($chacheKey, json_encode($params));
                Redis::EXPIRE($chacheKey, 86400);
            }
        }

        return $result;
    }

    /**
     * 渠道广告点击记录
     * @param $guid
     * @param $type 类型 oaid idfa
     * @param $code 具体的值
     */
    public function checkChannelPlatform($guid, $channelId, $type, $code)
    {
        $res = 0;
        do {
            if(empty($guid)) {
                break;
            }
            if(empty($channelId)) {
                break;
            }
            if(empty($code)) {
                break;
            }
            //从缓存获取数据
            $chacheKey = $this->channelPlatformRequestKey.$type.':'.strtolower($code);
            $requestLog = Redis::GET($chacheKey);
            
            if(empty($requestLog)) {
                $code = str_replace('-', '', $code);
                $chacheKey = $this->channelPlatformRequestKey.$type.':'.strtolower($code);
                $requestLog = Redis::GET($chacheKey);
            }
            write_log('device', '缓存信息' ,[$requestLog]);
            if(empty($requestLog)) {
                break;
            }
            $requestLog = json_decode($requestLog, true);

            //判断是否存在
            $oldInfo = DB::table($this->channelLogTable)->where('guid', $guid)->first();
            $oldInfo = self::objToArray($oldInfo);
            if(!empty($oldInfo)) {
                break;
            }

            $log = [];
            //vivo聚力
            if($requestLog['platform'] == 'vivo-juli') {
                if(!in_array($channelId, [400003])) {
                    break;
                }
                $log = [];
                $log['guid'] = $guid;
                $log['oaid'] = $requestLog['oaid'];
                $log['channel_id'] = $channelId;
                $log['platform'] = $requestLog['platform'];
                $log['rid'] = $requestLog['rid'];
                $log['request_info'] = json_encode($requestLog['request_info']);
                $logId = $this->insertChannelLog($log);
                $res = $logId;
            }
            //华为亨利
            if($requestLog['platform'] == 'huawei-hengli') {
                if(!in_array($channelId, [400001])) {
                    break;
                }
                $log = [];
                $log['guid'] = $guid;
                $log['oaid'] = $requestLog['oaid'];
                $log['channel_id'] = $channelId;
                $log['platform'] = $requestLog['platform'];
                $log['request_info'] = json_encode($requestLog['request_info']);
                $logId = $this->insertChannelLog($log);
                $res = $logId;
            }
            //快手韵洪
            if($requestLog['platform'] == 'kuaishou-yunhong') {
                if(!in_array($channelId, [900001])) {
                    break;
                }
                $log = [];
                $log['guid'] = $guid;
                $log['oaid'] = $requestLog['oaid'];
                $log['channel_id'] = $channelId;
                $log['platform'] = $requestLog['platform'];
                $log['rid'] = $requestLog['rid'];
                $log['request_info'] = json_encode($requestLog['request_info']);
                $logId = $this->insertChannelLog($log);
                $res = $logId;
            }
        } while (false);

        return $res;
    }

    public function getChannelLog($id)
    {
        $info = DB::table($this->channelLogTable)->where('id', $id)->first();
        $info = self::objToArray($info);
        if(!empty($info)) {
            $info['request_info'] = json_decode($info['request_info'], true);
        }

        return $info;
    }

    public function getChannelLogByGuid($guid)
    {
        $info = DB::table($this->channelLogTable)->where('guid', $guid)->first();
        $info = self::objToArray($info);
        if(!empty($info)) {
            $info['request_info'] = json_decode($info['request_info'], true);
        }

        return $info;
    }

    public function getChannelLogByuserId($userId)
    {
        $info = DB::table($this->channelLogTable)->where('user_id', $userId)->first();
        $info = self::objToArray($info);
        if(!empty($info)) {
            $info['request_info'] = json_decode($info['request_info'], true);
        }

        return $info;
    }

}
